﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head><title>Gestalt Widget Pack XBOX Gamercard Widget</title><style type="text/css"> html, body {background-color:Black; } </style>

<script type="text/javascript">    window.DLR = {}; DLR.path = "/dlr"; DLR.settings = { background: 'black' };</script>
<script src="/dlr/dlr.js" type="text/javascript"></script></head><body>

<script type="text/python" class="gamercard">
from System import *
from System.Net import *
from System.Windows import * 
from System.Windows.Controls import *
from System.Windows.Input import *
from System.Windows.Media import *
from System.Windows.Shapes import *
from System.Windows.Media.Animation import *
from System.Windows.Media.Imaging import * # for bitmap
from System.Net import * # for WebClient
from System.Windows.Resources import * # for WebClient
from System.Diagnostics import * # enables outputing to a debug window
from System.Windows.Markup import * # for XamlReader
from System.Collections.Generic import *
from System.Collections.ObjectModel import *
from System.Windows.Threading import DispatcherTimer
from System.IO import StringReader
import clr
clr.AddReference("System.Xml")
from System.Xml import *

gamerTag = "quietunruly1"
_xml = ""
_gametile = "";
gamer = None
serviceUrlFormat = "http://duncanmackenzie.net/services/GetXboxInfo.aspx?GamerTag={0}";
#serviceUrlFormat = "http://duncanmackenzie.net/services/XboxInfo.asmx?GamerTag={0}";

themeToLoad = "classic"

class CardTheme(object):
    BackgroundColor = None
    BackgroundImageUrl = None
    GameTileBackgroundColor = None
    GameTileBackgroundImageUrl = None
    GameTileBackgroundOpacity = None
    GameTileCount = None
    GameTileHighlightColor = None
    GameTileOutlineColor = None
    GameTileTextColor = None
    GameTileTextColor2 = None
    OfflineImageUrl = None
    OnlineImageUrl = None
    OutlineColor = None
    TextColor = None
    TextColor2 = None
    ThemeName = None
     
    def __init__(self, themename):
        self._themeName = themename
        self.BackgroundColor = Color.FromArgb(0xff, 240, 240, 240)
        self.BackgroundImageUrl = ""
        self.GameTileCount = 3
        self.GameTileBackgroundColor = Color.FromArgb(0xff, 0xcc, 0xcc, 0xcc)
        self.GameTileBackgroundImageUrl = ""
        self.GameTileHighlightColor = Color.FromArgb(0xff, 0xff, 0xff, 0xff)
        self.GameTileBackgroundOpacity = 0.2
        self.GameTileOutlineColor = Color.FromArgb(0xff, 0x99, 0x99, 0x99)
        self.GameTileTextColor = Color.FromArgb(0xff, 0x33, 0x33, 0x33)
        self.GameTileTextColor2 = Color.FromArgb(0xff, 0xff, 0xff, 0xff)
        self.OutlineColor = Color.FromArgb(0xff, 0x99, 0x99, 0x99)
        self.TextColor = Color.FromArgb(0xff, 0x33, 0x33, 0x33)
        self.TextColor2 = Color.FromArgb(0xff, 0xcc, 0xcc, 0xcc)
        self.OnlineImageUrl = "http://mschnlnine.vo.llnwd.net/d1/client/xbf/gc/t/lightgray/online.png"
        self.OfflineImageUrl = "http://mschnlnine.vo.llnwd.net/d1/client/xbf/gc/t/lightgray/offline.png"

class Game(object):
    Name = None
    TotalAchievements = None
    TotalGamerScore = None
    Image32Url = None
    Image64Url = None
    
class PresenceInfo(object):
    Info =  None
    Info2 =  None
    Online =  None
    StatusText = None
    Gamertag = None
    ProfileUrl = None
    TileUrl = None
    Country = None
    GamerScore = None
    Zone = None
    
    def SetFullInfo(self, value):
        pass
    def GetFullInfo(self):
        return String.Format("{0} {1}", self.Info, self.Info2)
    FullInfo = property(GetFullInfo, SetFullInfo)        
        
class XboxUserGameInfo(object):
    _Game = None
    LastPlayed = None
    Achievements = None
    GamerScore = None
    DetailsURL = None
    PresenceInfo = None
    
    def SetGame(self, value):
        self._Game = value
    def GetGame(self):
        return self._Game
    Game = property(GetGame, SetGame)
    
class XboxInfo(object):
    
    MessageUrl = None

    def __init__(self, xml):
        self._xml = xml
        self.PresenceInfo = PresenceInfo()
        self.RecentGames = List[XboxUserGameInfo]()
        self.AccountStatus = None
        self.Country = None
        self.GamerScore = None
        self.GamerTag = None
        self.ProfileUrl = None
        self.Reputation = None
        self.ReputationImageUrl = None
        self.TileUrl = None
        self.Zone = None
        
        reader = XmlReader.Create(StringReader(self._xml))
        reader.ReadToFollowing("AccountStatus")
        self.AccountStatus = reader.ReadElementContentAsString()
        
        if self.AccountStatus != "Unknown":
            reader.ReadToFollowing("Info")
            self.PresenceInfo.Info = reader.ReadElementContentAsString()
            reader.ReadToFollowing("Info2")
            self.PresenceInfo.Info2 = reader.ReadElementContentAsString()
            reader.ReadToFollowing("Online")
            self.PresenceInfo.Online = reader.ReadElementContentAsString()
            reader.ReadToFollowing("StatusText")
            self.PresenceInfo.StatusText = reader.ReadElementContentAsString()
            reader.ReadToFollowing("Gamertag")
            self.GamerTag = reader.ReadElementContentAsString()
            reader.ReadToFollowing("ProfileUrl")
            self.ProfileUrl = reader.ReadElementContentAsString()
            reader.ReadToFollowing("TileUrl")
            self.TileUrl = reader.ReadElementContentAsString()
            reader.ReadToFollowing("Country")
            self.Country = reader.ReadElementContentAsString()
            reader.ReadToFollowing("GamerScore")
            self.GamerScore = reader.ReadElementContentAsString()
            reader.ReadToFollowing("Zone")
            self.Zone = reader.ReadElementContentAsString()
            item = None
            while (reader.Read()):
                if reader.NodeType == XmlNodeType.Element and reader.Name == "XboxUserGameInfo":
                    item = XboxUserGameInfo()
                    item.Game = Game()
                    reader.ReadToFollowing("Name")
                    item.Game.Name = reader.ReadElementContentAsString()
                    reader.ReadToFollowing("TotalAchievements")
                    item.Game.TotalAchievements = reader.ReadElementContentAsString()
                    reader.ReadToFollowing("TotalGamerScore")
                    item.Game.TotalGamerScore = reader.ReadElementContentAsString()
                    reader.ReadToFollowing("Image32Url")
                    item.Game.Image32Url = reader.ReadElementContentAsString()
                    reader.ReadToFollowing("Image64Url")
                    item.Game.Image64Url = reader.ReadElementContentAsString()
                    reader.ReadToFollowing("LastPlayed")
                    item.LastPlayed = reader.ReadElementContentAsDateTime()
                    reader.ReadToFollowing("Achievements")
                    item.Achievements = reader.ReadElementContentAsString()
                    reader.ReadToFollowing("GamerScore")
                    item.GamerScore = reader.ReadElementContentAsString()
                    reader.ReadToFollowing("DetailsURL")
                    item.DetailsURL = reader.ReadElementContentAsString()
                    self.RecentGames.Add(item)
        else:
            self.GamerTag = "??????"
            
    def SetMessageUrl(self, value):
        pass
    def GetMessageUrl(self):
        return string.Format("http://live.xbox.com/en-US/profile/MessageCenter/SendMessage.aspx?gt={0}", self._gamerTag)
    MessageUrl = property(GetMessageUrl, SetMessageUrl)            
    
class XboxUserGameInfo(object):
    Achievments = None
    DetailsUrl = None
    Game = None
    GamerScore = None
    LastPlayed = None

    def __init__(self):
        self.Game = Game()
        
class GameTile(Grid):
    hlOn = None
    hlOff = None
    expanded = False
    LastChild = False

    def __init__(self, xaml):
        self.Content = XamlReader.Load(xaml)
        self.Children.Add(self.Content)
        
        self.hlOn = Storyboard()
        da =  DoubleAnimation()
        da.To = 1.0
        da.Duration = TimeSpan.FromMilliseconds(300.0)
        Storyboard.SetTarget(da, self.Content.Hightlight)
        Storyboard.SetTargetProperty(da, PropertyPath("(UIElement.Opacity)"))
        self.hlOn.Children.Add(da)
        self.hlOff =  Storyboard()
        da =  DoubleAnimation()
        da.To = 0.0
        da.Duration = TimeSpan.FromMilliseconds(300.0)
        Storyboard.SetTarget(da, self.Content.Hightlight)
        Storyboard.SetTargetProperty(da, PropertyPath("(UIElement.Opacity)"))
        self.hlOff.Children.Add(da)
        
        storyboard =  Storyboard()
        timeline =  DoubleAnimation()
        timeline.To = 1.0
        timeline.Duration = TimeSpan.FromMilliseconds(800.0)
        Storyboard.SetTarget(timeline, self.Content.LayoutRoot)
        Storyboard.SetTargetProperty(timeline,  PropertyPath("(UIElement.Opacity)"))
        storyboard.Children.Add(timeline)
        storyboard.BeginTime =  TimeSpan.FromMilliseconds(0)
        storyboard.Begin()
        
        def shrinkTile():
            self.Content.Cursor = Cursors.Hand
            self.Content.rootShrink.Begin()
            if self.LastChild:
                self.Content.rootDown.Begin()  
            self.expanded = False
            
        def expandTile():
            self.SetValue(Canvas.ZIndexProperty, 0x3e8)
            self.Content.Cursor = Cursors.Arrow
            self.Content.rootExpand.Begin()
            if self.LastChild:
                self.Content.rootUp.Begin();
            self.expanded = True
        
        def LayoutRoot_MouseEnter(sender, e):
            self.hlOn.Begin()
            
        def LayoutRoot_MouseLeave(sender, e):
            self.hlOff.Begin()
            if self.expanded:
                pass
                shrinkTile()
                
        def LayoutRoot_MouseLeftButtonUp(sender, e):
            if self.expanded:
                shrinkTile()
            else:
                expandTile()
                
        def rootShrink_Completed(sender, e):
            self.SetValue(Canvas.ZIndexProperty, 0);
            
        self.Content.LayoutRoot.MouseEnter += LayoutRoot_MouseEnter
        self.Content.LayoutRoot.MouseLeave += LayoutRoot_MouseLeave
        self.Content.LayoutRoot.MouseLeftButtonUp += LayoutRoot_MouseLeftButtonUp
        self.Content.rootShrink.Completed += rootShrink_Completed
        
    def SetX(self, value):
      self.SetValue(Canvas.LeftProperty, Convert.ToDouble(value))
    def GetX(self):
      return self.GetValue(Canvas.LeftProperty)
    X = property(GetX, SetX)

    def SetY(self, value):
      self.SetValue(Canvas.TopProperty, Convert.ToDouble(value))
    def GetY(self):
      return self.GetValue(Canvas.TopProperty)
    Y = property(GetY, SetY)        
        
def HexStringToColor(hexColor):
    c = Color()
    r = Convert.ToUInt32(hexColor.Substring(1, 2), 16)
    g = Convert.ToUInt32(hexColor.Substring(3, 2), 16)
    b = Convert.ToUInt32(hexColor.Substring(5, 2), 16)
    c = Color.FromArgb(255, r, g, b)				
    return c
        
def ParseParamsToTheme(Params, theme):
    if Params.ContainsKey("bgcolor"):
        theme.BackgroundColor = HexStringToColor(Params["bgcolor"])
    if Params.ContainsKey("bgimage"):
        theme.BackgroundImageUrl = Params["bgimage"]
    if Params.ContainsKey("textcolor"):
        theme.TextColor = HexStringToColor(Params["textcolor"])
    if Params.ContainsKey("textcolor2"):
        theme.TextColor2 = HexStringToColor(Params["textcolor2"])
    if Params.ContainsKey("olcolor"):
        theme.OutlineColor = HexStringToColor(Params["olcolor"])
    if Params.ContainsKey("gtcount"):
        theme.GameTileCount = int.Parse(Params["gtcount"])
    if Params.ContainsKey("gtbgcolor"):
        theme.GameTileBackgroundColor = HexStringToColor(Params["gtbgcolor"])
    if Params.ContainsKey("gtbgimage"):
        theme.GameTileBackgroundImageUrl = Params["gtbgimage"]
    if Params.ContainsKey("gttextcolor"):
        theme.GameTileTextColor = HexStringToColor(Params["gttextcolor"])
    if Params.ContainsKey("gttextcolor2"):
        theme.GameTileTextColor2 = HexStringToColor(Params["gttextcolor2"])
    if Params.ContainsKey("gtolcolor"):
        theme.GameTileOutlineColor = HexStringToColor(Params["gtolcolor"])
    if Params.ContainsKey("gthlcolor"):
        theme.GameTileHighlightColor = HexStringToColor(Params["gthlcolor"])
    if Params.ContainsKey("gtbgopacity"):
        theme.GameTileBackgroundOpacity = Double.Parse(Params["gtbgopacity"])
    if Params.ContainsKey("onlineimage"):
        theme.OnlineImageUrl = Params["onlineimage"]
    if Params.ContainsKey("offlineimage"):
        theme.OfflineImageUrl = Params["offlineimage"]
        
def applyGameTileStyle(gt):
    if theme.GameTileBackgroundImageUrl != String.Empty:
        brush = ImageBrush()
        brush.ImageSource = BitmapImage(Uri(theme.GameTileBackgroundImageUrl))
        gt.Content.LayoutRoot.Background = brush
    else:
        gt.Content.LayoutRoot.Background = SolidColorBrush(theme.GameTileBackgroundColor)
    brush2 = SolidColorBrush(theme.GameTileTextColor)
    gt.Content.GamerTitleText.Foreground = gt.Content.GamerScoreText.Foreground = gt.Content.GamerScoreSplit.Foreground = gt.Content.GamerScoreTotal.Foreground = gt.Content.AchievementText.Foreground = gt.Content.AchievementSplit.Foreground = gt.Content.AchievementTotal.Foreground = gt.Content.InfoText.Foreground = gt.Content.InfoAText.Foreground = brush2;
    brush2 = SolidColorBrush(theme.GameTileTextColor2);
    gt.Content.GamerSymbol.Foreground = gt.Content.AchievementSymbol.Foreground = brush2;
    brush3 = SolidColorBrush(theme.GameTileOutlineColor);
    gt.Content.AvatarOutline.Fill = gt.Content.GamerScoreBackground.Fill = gt.Content.AchievementBackground.Fill = brush3;
    gt.Content.Hightlight.BorderBrush = SolidColorBrush(theme.GameTileHighlightColor);
    gt.Content.HighlightFill.Opacity = theme.GameTileBackgroundOpacity;    
        
def loadRecentGames():
    me.LinkBack.Text = "loading recent games..."
    me.gameContainer.Children.Clear()
    num2 = 0.0
    gameTileCount = theme.GameTileCount
    me.LayoutRoot.Height = 84 + (40 * theme.GameTileCount)
    me.Height = 84 + (40 * theme.GameTileCount)
    if gamer.RecentGames.Count < gameTileCount:
        gameTileCount = gamer.RecentGames.Count;
    for i in range( 0, gameTileCount):
        gt = GameTile(_gametile)
        applyGameTileStyle(gt)
        
        #gt.DataContext = gamer.RecentGames[i] # Databinding Broken????
        info = gamer.RecentGames[i]
        gt.Content.TileImage.Source = BitmapImage(Uri(info.Game.Image64Url))
        gt.Content.HighlightFill.ImageSource =  BitmapImage( Uri(info.Game.Image64Url))
        gt.Content.GamerTitleText.Text = info.Game.Name
        gt.Content.GamerScoreText.Text = info.GamerScore
        gt.Content.GamerScoreTotal.Text = info.Game.TotalGamerScore
        gt.Content.AchievementText.Text = info.Achievements
        gt.Content.AchievementTotal.Text = info.Game.TotalAchievements
        gt.Content.InfoAText.Text = info.LastPlayed.ToString()
        gt.Y = num2
        if i == gameTileCount - 1:
            gt.LastChild = True
        me.gameContainer.Children.Add(gt)
        num2 = num2 + 40.0;
        
    me.LinkBack.Text = ""
        
def applyGamer():
    me.LinkBack.Text = "applying GamerTag data..."
    if (gamer.GamerTag != "??????") and (gamer.GamerTag != ""):
        if gamer.PresenceInfo.StatusText != "Offline":
            me.OnlineImage.Visibility = Visibility.Visible
            me.OfflineImage.Visibility = Visibility.Collapsed
        else:
            me.OnlineImage.Visibility = Visibility.Collapsed
            me.OfflineImage.Visibility = Visibility.Visible
            
        me.DataContext = gamer # has no effect
        me.tileUrl.Source = BitmapImage(Uri(gamer.TileUrl))
        me.profileUrl.NavigateUri = Uri(gamer.ProfileUrl)
        me.profileUrl2.NavigateUri = Uri(gamer.ProfileUrl)
        me.GamerTagText.Text = gamer.GamerTag
        me.GamerScoreText.Text = gamer.GamerScore
        me.InfoText.Text = gamer.PresenceInfo.FullInfo
        
        loadRecentGames()
    else:
        me.LinkBack.Text = "unknown gamertag..."

def loadGamer(xmlContent):
    global gamer
    me.LinkBack.Text = "loading GamerTag data..."
    gamer = XboxInfo(xmlContent);
    applyGamer();
    
def applyTheme():
    me.LinkBack.Text = "applying theme...";
    if theme.BackgroundImageUrl != "":
        brush = ImageBrush()
        brush.ImageSource = BitmapImage(Uri(theme.BackgroundImageUrl))
        me.LayoutRoot.Background = brush
    else:
        me.LayoutRoot.Background = SolidColorBrush(theme.BackgroundColor)
    brush2 = SolidColorBrush(theme.TextColor)
    me.GamerTagText.Foreground = me.GamerScoreText.Foreground = me.InfoText.Foreground = brush2
    brush2 = SolidColorBrush(theme.TextColor2)
    me.GamerSymbol.Foreground = me.LinkBack.Foreground = brush2
    brush3 = SolidColorBrush(theme.OutlineColor)
    me.AvatarOutline.Fill = me.GamerScoreBackground.Fill = brush3
    me.OnlineImage.Source = BitmapImage(Uri(theme.OnlineImageUrl))
    me.OfflineImage.Source = BitmapImage(Uri(theme.OfflineImageUrl))
    requestGamerXml(gamerTag)

def XmlLoaded(sender, e):
    global _xml
    if e.Error == None:
        _xml = e.Result
        loadGamer(_xml)
    else:
        me.LinkBack.Text = "error contacting Xbox LIVE service..."
        
def GameTileXamlLoaded(sender, e):
    global _gametile
    _gametile = e.Result
    if e.Error == None:
        lpOn = Storyboard()
        da = DoubleAnimation()
        da.To = 1.0
        da.Duration = TimeSpan.FromMilliseconds(300.0)
        Storyboard.SetTarget(da, me.LinkPanel)
        Storyboard.SetTargetProperty(da, PropertyPath("(UIElement.Opacity)"))
        lpOn.Children.Add(da)
        lpOff = Storyboard()
        da = DoubleAnimation()
        da.To = 0.0
        da.Duration = TimeSpan.FromMilliseconds(300.0)
        Storyboard.SetTarget(da, me.LinkPanel)
        Storyboard.SetTargetProperty(da, PropertyPath("(UIElement.Opacity)"))
        lpOff.Children.Add(da);    
        LoadTheme()
    else:
        me.LinkBack.Text = "error loading GameTile..."
        
def ThemeLoaded(sender, e):
    global theme
    if e.Error == None:
        para = Dictionary[String, String]()
        strArray = e.Result.Split(',');
        length = 0
        for i in range( 0, strArray.Count):
            length = strArray[i].IndexOf("=")
            para.Add(strArray[i].Substring(0, length), strArray[i].Substring(length + 1));
        theme = CardTheme(theme.ThemeName);
        ParseParamsToTheme(para, theme);
        applyTheme()
    else:
        me.LinkBack.Text = "error loading Theme..."              

from Microsoft.Scripting.Silverlight.DynamicApplication import MakeUri

def requestGamerXml(gt):
    me.LinkBack.Text = "calling Xbox LIVE service..."
    client = WebClient()
    client.DownloadStringCompleted += XmlLoaded
    #client.DownloadStringAsync(MakeUri("gamertag.xml?gamertag=" + gt))
    #client.DownloadStringAsync(Uri("http://duncanmackenzie.net/services/GetXboxInfo.aspx?GamerTag=" + gt, UriKind.Absolute))
    client.DownloadStringAsync(Uri(String.Format(serviceUrlFormat, gt), UriKind.Absolute))

def LoadGameTileXaml():
    client = WebClient()
    client.DownloadStringCompleted += GameTileXamlLoaded
    client.DownloadStringAsync(MakeUri("gametile.xaml"))
    
def LoadTheme():
    me.LinkBack.Text = "loading Theme..."
    client = WebClient()
    client.DownloadStringCompleted += ThemeLoaded
    client.DownloadStringAsync(MakeUri(themeToLoad + ".txt"))    

theme = CardTheme("")
LoadGameTileXaml()
</script>

<script id="gamercard" type="application/xml+xaml" width="200" height="300" src="gamercard.xaml"></script>

</body>
</html>
